<template>
  <view class="coupon-list-page">
    <!-- 导航栏 -->
    <NavBar title="我的优惠券" />

    <!-- 选项卡 -->
    <nut-tabs v-model="activeTab" @click="onTabChange">
      <nut-tab-pane title="未使用" pane-key="unused" />
      <nut-tab-pane title="已使用" pane-key="used" />
      <nut-tab-pane title="已过期" pane-key="expired" />
    </nut-tabs>

    <!-- 优惠券列表 -->
    <view class="coupon-content">
      <!-- 空优惠券提示 -->
      <nut-empty v-if="couponList.length === 0" description="暂无优惠券" image="empty">
        <template #footer>
          <nut-button type="primary" size="small" @click="goCouponCenter">去领券</nut-button>
        </template>
      </nut-empty>

      <!-- 优惠券列表 -->
      <view v-else class="coupon-list">
        <view 
          v-for="(item, index) in couponList" 
          :key="index"
          class="coupon-item"
          :class="{
            'used': item.status === 'used',
            'expired': item.status === 'expired'
          }"
          @click="useCoupon(item)"
        >
          <view class="coupon-left">
            <view class="coupon-amount">
              <text class="symbol">¥</text>
              <text class="value">{{ item.amount }}</text>
            </view>
            <view class="coupon-condition">满{{ item.minAmount }}元可用</view>
          </view>
          <view class="coupon-right">
            <view class="coupon-name">{{ item.name }}</view>
            <view class="coupon-scope">{{ item.scope }}</view>
            <view class="coupon-time">{{ item.validTimeDesc }}</view>
            <view class="coupon-status" v-if="item.status !== 'unused'">
              <image 
                :src="item.status === 'used' ? usedStamp : expiredStamp" 
                class="status-stamp"
              />
            </view>
            <view class="coupon-btn" v-if="item.status === 'unused' && fromOrder">
              <nut-button size="small" type="primary">立即使用</nut-button>
            </view>
          </view>
          <view class="coupon-circle-top"></view>
          <view class="coupon-circle-bottom"></view>
        </view>
      </view>
    </view>

    <!-- 领券入口 -->
    <view class="coupon-center" v-if="activeTab === 'unused'">
      <nut-button type="primary" block @click="goCouponCenter">去领券中心</nut-button>
    </view>

    <!-- 优惠券码兑换 -->
    <view class="coupon-exchange" v-if="activeTab === 'unused'">
      <view class="exchange-title">优惠券兑换</view>
      <view class="exchange-form">
        <nut-input v-model="couponCode" placeholder="请输入优惠券码" />
        <nut-button type="primary" @click="exchangeCoupon">兑换</nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import type { CouponItem } from '@/api/types'
import { useLoading } from '@/hooks/useLoading'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const fromOrder = router?.params?.from === 'order'
const selectedCategoryId = router?.params?.categoryId
const minAmount = router?.params?.amount

// 选项卡
const activeTab = ref('unused')

// 优惠券列表
const couponList = ref<CouponItem[]>([])

// 优惠券码
const couponCode = ref('')

// 加载状态
const { loading, showLoading, hideLoading } = useLoading()

// 状态图片
const usedStamp = 'https://img01.yzcdn.cn/vant/coupon-used.png'
const expiredStamp = 'https://img01.yzcdn.cn/vant/coupon-expired.png'

// 选项卡切换
const onTabChange = () => {
  couponList.value = []
  getCouponList()
}

// 使用优惠券
const useCoupon = (coupon: CouponItem) => {
  // 跳转到优惠券详情页，传递必要参数
  let url = `/pages/coupon/detail?id=${coupon.id}`
  
  // 如果是从订单页面跳转来的，需要传递订单相关参数
  if (fromOrder) {
    url += `&from=order`
    if (minAmount) url += `&amount=${minAmount}`
    if (selectedCategoryId) url += `&categoryId=${selectedCategoryId}`
  }
  
  Taro.navigateTo({ url })
  
  // 以下是原有逻辑，现在移动到详情页中处理
  // if (coupon.status !== 'unused') {
  //   Taro.showToast({
  //     title: coupon.status === 'used' ? '该优惠券已使用' : '该优惠券已过期',
  //     icon: 'none'
  //   })
  //   return
  // }
  
  // if (fromOrder) {
  //   // 如果是从订单页面跳转来的，选择优惠券后返回
  //   const pages = Taro.getCurrentPages()
  //   const prevPage = pages[pages.length - 2]
    
  //   // 向上一页传递选中的优惠券
  //   if (prevPage) {
  //     // 实际项目中应该使用更好的状态管理方式
  //     prevPage.$instance.ctx.selectedCoupon = coupon
      
  //     Taro.showToast({
  //       title: '已选择优惠券',
  //       icon: 'success'
  //     })
  //   }
    
  //   Taro.navigateBack()
  // } else {
  //   // 否则跳转到商品列表
  //   if (coupon.categoryId) {
  //     Taro.navigateTo({
  //       url: `/pages/category/category-detail?id=${coupon.categoryId}&name=${coupon.scope}`
  //     })
  //   } else {
  //     // 全场通用券跳转到首页
  //     Taro.switchTab({
  //       url: '/pages/index/index'
  //     })
  //   }
  // }

}

// 去购物
const goShopping = () => {
  Taro.switchTab({
    url: '/pages/index/index'
  })
}

// 去领券中心
const goCouponCenter = () => {
  Taro.navigateTo({
    url: '/pages/coupon/center'
  })
}

// 兑换优惠券
const exchangeCoupon = async () => {
  if (!couponCode.value) {
    return Taro.showToast({
      title: '请输入优惠券码',
      icon: 'none'
    })
  }
  
  try {
    showLoading('兑换中...')
    await userApi.exchangeCoupon(couponCode.value)
    
    Taro.showToast({
      title: '兑换成功',
      icon: 'success'
    })
    
    // 重新获取优惠券列表
    getCouponList()
    
    // 清空输入框
    couponCode.value = ''
  } catch (error) {
    Taro.showToast({
      title: '兑换失败，请检查优惠券码是否正确',
      icon: 'none'
    })
  } finally {
    hideLoading()
  }
}

// 获取优惠券列表
const getCouponList = async () => {
  try {
    showLoading('加载中...')
    
    // 调用API获取优惠券列表
    const res = await userApi.getCouponList({
      status: activeTab.value
    })
    
    // 根据订单金额和分类筛选可用优惠券
    if (fromOrder && minAmount && activeTab.value === 'unused') {
      couponList.value = res.data.filter((coupon: CouponItem) => {
        // 判断金额是否满足条件
        const isAmountValid = Number(coupon.minAmount) <= Number(minAmount)
        
        // 判断分类是否匹配（全场通用或者分类匹配）
        const isCategoryValid = !coupon.categoryId || !selectedCategoryId || 
          coupon.categoryId === selectedCategoryId
        
        return isAmountValid && isCategoryValid
      })
    } else {
      couponList.value = res.data
    }
    
    // 如果API调用失败，使用模拟数据
  } catch (error) {
    console.error('获取优惠券列表失败', error)
    
    // 模拟数据
    if (activeTab.value === 'unused') {
      couponList.value = [
        {
          id: '1',
          name: '新人专享券',
          amount: '10',
          minAmount: '100',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-06-01 ~ 2023-07-01',
          status: 'unused'
        },
        {
          id: '2',
          name: '满减优惠券',
          amount: '50',
          minAmount: '300',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-06-01 ~ 2023-07-01',
          status: 'unused'
        }
      ]
    } else if (activeTab.value === 'used') {
      couponList.value = [
        {
          id: '3',
          name: '满减优惠券',
          amount: '20',
          minAmount: '200',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-05-01 ~ 2023-06-01',
          status: 'used'
        }
      ]
    } else {
      couponList.value = [
        {
          id: '4',
          name: '满减优惠券',
          amount: '30',
          minAmount: '200',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-04-01 ~ 2023-05-01',
          status: 'expired'
        }
      ]
    }
    
    Taro.showToast({
      title: '获取优惠券列表失败',
      icon: 'none'
    })
  } finally {
    hideLoading()
  }
}

// 监听选项卡变化
watch(() => activeTab.value, () => {
  getCouponList()
})

// 组件挂载时初始化
onMounted(() => {
  getCouponList()
})

// 检查优惠券是否可用
const isCouponAvailable = (coupon: CouponItem) => {
  if (coupon.status !== 'unused') return false
  
  // 如果是从订单页面跳转来的，需要检查金额是否满足条件
  if (fromOrder && minAmount) {
    return Number(coupon.minAmount) <= Number(minAmount)
  }
  
  return true
}
</script>

<style lang="scss" scoped>
.coupon-list-page {
  padding-bottom: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .coupon-content {
    padding: 10px;
    
    .coupon-list {
      .coupon-item {
        position: relative;
        display: flex;
        margin-bottom: 15px;
        height: 100px;
        background: linear-gradient(to right, #ff9500, #ff6000);
        border-radius: 8px;
        color: #fff;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(255, 149, 0, 0.2);
        
        &.used,
        &.expired {
          background: linear-gradient(to right, #bbb, #999);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .coupon-left {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 120px;
          border-right: 1px dashed rgba(255, 255, 255, 0.3);
          
          .coupon-amount {
            display: flex;
            align-items: baseline;
            
            .symbol {
              font-size: 16px;
              margin-right: 2px;
            }
            
            .value {
              font-size: 30px;
              font-weight: bold;
            }
          }
          
          .coupon-condition {
            font-size: 12px;
            margin-top: 5px;
          }
        }
        
        .coupon-right {
          flex: 1;
          padding: 15px;
          position: relative;
          
          .coupon-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .coupon-scope {
            font-size: 12px;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .coupon-time {
            font-size: 12px;
            opacity: 0.8;
          }
          
          .coupon-status {
            position: absolute;
            right: 15px;
            top: 15px;
            
            .status-stamp {
              width: 50px;
              height: 50px;
              opacity: 0.8;
            }
          }
          
          .coupon-btn {
            position: absolute;
            right: 15px;
            bottom: 15px;
          }
        }
        
        .coupon-circle-top,
        .coupon-circle-bottom {
          position: absolute;
          left: 110px;
          width: 20px;
          height: 20px;
          background-color: #f5f5f5;
          border-radius: 50%;
        }
        
        .coupon-circle-top {
          top: -10px;
        }
        
        .coupon-circle-bottom {
          bottom: -10px;
        }
      }
    }
  }
  
  .coupon-center,
  .coupon-exchange {
    margin: 15px 10px;
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  }
  
  .coupon-exchange {
    margin-top: 10px;
    
    .exchange-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 10px;
      color: #333;
    }
    
    .exchange-form {
      display: flex;
      
      .nut-input {
        flex: 1;
        margin-right: 10px;
      }
    }
  }
  
  :deep(.nut-empty) {
    padding: 40px 0;
  }
}
</style>